import os

total_size, file_num, dir_num = 0, 0, 0


def traverse(path):
    """用于遍历指定目录path"""
    global total_size, file_num, dir_num
    if not os.path.isdir(path):
        print(f"{path}不是目录或者不存在")
        return
    for dirname in os.listdir(path):
        sub_path = os.path.join(path, dirname)
        if os.path.isfile(sub_path):
            file_num += 1
            total_size += os.path.getsize(sub_path)
        elif os.path.isdir(sub_path):
            dir_num += 1
            traverse(sub_path)


def size_convert(size):
    """将文件的总字节数换算为单位B、KB、MB或者GB"""
    K, M, G = 1024, 1024 ** 2, 1024 ** 3
    if size >= G:
        return f"{size / G:.2f}GB"
    elif size >= M:
        return f"{size / M:.2f}MB"
    if size >= K:
        return f"{size / K:.2f}KB"
    else:
        return f"{size:.2f}B"


def output(path):
    """用于输出目录的位置、大小以及文件和文件夹的个数"""
    if os.path.isdir(path):
        print("类型：文件夹")
    else:
        return
    print("位置：", path)
    print(f"大小：{size_convert(total_size)}(包含{total_size}字节)")
    print(f"包含{file_num}个文件，{dir_num}个文件夹")


if __name__ == "__main__":
    path = "./test2024"
    traverse(path)
    output(path)
